import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/enums.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_search_result_entity.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/local_data/search_keyword_data.dart';
import 'package:osc/res/colors.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/search/search_article.dart';
import 'package:osc/ui/pages/search/search_user.dart';
import 'package:osc/ui/widgets/button/pd_button.dart';
import 'package:osc/ui/widgets/post/osc_search_article_widget.dart';
import 'package:osc/ui/widgets/project/osc_search_soft_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_user_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class Search extends StatefulWidget{
  final bool showLeading;

  const Search({Key key, this.showLeading = false}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new SearchState(showLeading);
  }
}

class SearchState extends State<Search> with SingleTickerProviderStateMixin{
  final bool showLeading;
  SearchState(this.showLeading);

  TextEditingController editingController;
  FocusNode fnKeyword;

  HttpRepository httpRepository;
  String pageToken;

  String keyword;

  bool isLoadData = false;
  bool isHistoryPage = true;

  int keywordSize;
  List<String> keywordList;

  int softSize = 0;
  int softwareTotalCount = 0;
  List<OscSearchArticle> softWares;

  int userSize = 0;
  int userTotalCount = 0;
  List<OscUser> users;

  int articleSize = 0;
  int articleTotalCount = 0;
  List<OscSearchArticle> articles;

  int order = 0;//0-按相关度|3-按时间


  RefreshController refreshController = RefreshController(initialRefresh: false);


  @override
  void initState() {
    super.initState();
    editingController = new TextEditingController();
    fnKeyword = FocusNode();
    httpRepository = new HttpRepository();
    keywordList = SearchKeywordData().getList();
  }

  @override
  void dispose() {
    super.dispose();
    editingController?.dispose();
    refreshController.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildBar(),
      body: buildBody(),
    );
  }

  buildBar(){
    return PreferredSize(
      child: AppBar(
        automaticallyImplyLeading: showLeading,
        titleSpacing: Dimens.gap_view_big,
        title: buildSearch(),
      ),
      preferredSize: Size.fromHeight(Dimens.view_tab_bar_height),
    );
  }

  Widget buildSearch(){
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
            margin: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.black12, width: Dimens.gap_divider_height_smallest),
              borderRadius: BorderRadius.circular(Dimens.view_radius_size_biggest),
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: editingController,
                    focusNode: fnKeyword,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(Dimens.gap_view_bigger),
                      prefixIcon: Icon(Icons.search, color: Colors.black26,),
                      border: buildTextFieldBorder(),
                      focusedBorder: buildTextFieldBorder(),
                      enabledBorder: buildTextFieldBorder(),
                      disabledBorder: buildTextFieldBorder(),
                      errorBorder: buildTextFieldBorder(),
                      focusedErrorBorder: buildTextFieldBorder(),
                      hintStyle: MyTextStyle.TEXT_FIELD_COMMENT_HINT,
                      hintText: "搜索软件、博客、问答、用户",
                    ),
                    style: MyTextStyle.TEXT_FIELD_COMMENT,

                    inputFormatters: [LengthLimitingTextInputFormatter(18)],
                    textInputAction: TextInputAction.search,
                    onChanged: (text){
                      setState(() {
                        keyword = text;
                        if(!isHistoryPage && StringUtil.isEmpty(text)){
                          isHistoryPage = true;
                        }
                      });
                    },
                    onSubmitted: (text){
                      keyword = text;
                      search(keyword);
                    },
                  ),
                ),
                IconButton(
                  icon: Icon(
                    Icons.clear,
                    color: StringUtil.isEmpty(editingController.text)? Colors.transparent : Colors.black26,),
                  onPressed: (){
                    setState(() {
                      keyword = null;
                      editingController.clear();
                      if(!isHistoryPage){
                        isHistoryPage = true;
                      }
                    });
                  },
                ),
              ],
            ),
          ),
        ),
        SmallWidgets.buildAction(
            textColor: Colors.green,
            data: "搜索",
            onTap: (){
              search(keyword);
            }
        ),
      ],
    );
  }

  buildTextFieldBorder(){
    return InputBorder.none;
  }

  buildBody(){
    return SmartRefresher(
      controller: refreshController,
      enablePullUp: true,
      onLoading: loadData,
      onRefresh: refresh,
      child: isHistoryPage? buildKeywordHistory() : buildSearchResult(),
    );
  }

  buildKeywordHistory(){
    return ListView(
      children: <Widget>[
        Container(
          color: Colors.black12,
          padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal, horizontal: Dimens.gap_view_bigger),
          child: Text("历史搜索关键词", style: MyTextStyle.BLACK_BUTTON,),
        ),
        buildHistoryListView(),
        Divider(color: Colors.transparent,),
        Offstage(
          offstage: keywordSize == 0,
          child: PdButton(
            data: "清空搜索历史",
            textStyle: MyTextStyle.BLACK_BUTTON,
            width: ScreenUtil.getScreenW(context),
            height: Dimens.view_button_height_normal,
            borderColor: Colors.black12,
            bg: Colors.white,
            onTap: (){
              _clearKeyword();
            },
          ),
        )
      ],
    );
  }

  Widget buildHistoryListView(){
    keywordSize = keywordList?.length??0;
    return ListView.separated(
      shrinkWrap: true,
      primary: false,
      itemBuilder: (BuildContext context, int index) {
        return buildHistoryListItem(keywordList.elementAt(index));
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider(height: Dimens.gap_divider_height_smallest,);
      },
      itemCount: keywordSize,
    );
  }

  Widget buildHistoryListItem(String keyword){
    return InkWell(
        onTap: (){
          search(keyword);
        },
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_bigger),
          child: Row(
          children: <Widget>[
            Icon(Icons.search, color: Colors.black26,),
            Text(" $keyword"),
          ],
        ),
      ),
    );
  }

  buildSearchResult(){
    return ListView(
      children: <Widget>[
        buildSoftTab(),
        buildSoftwareListView(),
        buildUserTab(),
        buildUserListView(),
        buildArticleTab(),
        buildArticleListView(),
      ],
    );
  }

  buildTab({@required String catalog, @required Widget child}){
    return Container(
      decoration: BoxDecoration(
        color: Colours.bg_page,
        border: Border.all(
          color: Colors.black12,
          width: Dimens.gap_divider_height_smallest,
        )
      ),
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_big),
      child: Row(
        children: <Widget>[
          Expanded(
              child: Text(catalog, style: MyTextStyle.USER_LIST_TITLE,),
          ),
          child,
        ],
      ),
    );
  }

  buildSoftTab(){
    return buildTab(
      catalog: "软件",
      child: buildTabChild(
        data: "查看其余$softwareTotalCount款软件",
        onTap: (){
          jump2Page(SearchArticle(type: SearchType.SOFTWARE, keyword: keyword,));
        },
      ),
    );
  }

  buildUserTab(){
    return buildTab(
        catalog: "用户",
        child: buildTabChild(
            data: "查看其余$userTotalCount位用户",
            onTap: (){
              jump2Page(SearchUser(keyword: keyword,));
            },
        ),
    );
  }

  buildArticleTab(){
    return buildTab(
      catalog: "文章",
      child: Row(
        children: <Widget>[
          buildTabChild(
            data: "按相关度",
            onTap: (){
              if(order != 0){
                articles.clear();
                articleSize = 0;
                pageToken = null;
                order = 0;
                loadData();
              }
            },
            style: TextStyle(color: order == 0? Colors.green : Colors.black87, fontSize: Dimens.font_sp12),
          ),
          Text(" | ", style: MyTextStyle.USER_LIST_TITLE,),
          buildTabChild(
            data: "按时间",
            onTap: (){
              if(order != 3){
                articles.clear();
                articleSize = 0;
                pageToken = null;
                order = 3;
                loadData();
              }
            },
            style: TextStyle(color: order == 3? Colors.green : Colors.black87, fontSize: Dimens.font_sp12),
          )
        ],
      ),
    );
  }

  buildTabChild({@required String data, @required Function onTap, TextStyle style = MyTextStyle.GREEN_BUTTON}){
    return InkWell(
      onTap: (){
        onTap();
      },
      child: Text(data, style: style,),
    );
  }

  buildListView({@required Widget Function(int index)itemWidget, @required itemCount}){
    return ListView.separated(
      shrinkWrap: true,
      primary: false,
      itemBuilder: (BuildContext context, int index) {
        return itemWidget(index);
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider(height: Dimens.gap_divider_height_smallest,);
      },
      itemCount: itemCount,
    );
  }

  Widget buildSoftwareListView(){
    return buildListView(
        itemWidget: (index){
          return OscSearchSoftWidget(software: softWares.elementAt(index),);
        },
        itemCount: softSize
    );
  }

  Widget buildUserListView(){
    return buildListView(
        itemWidget: (index){
          return OscUserWidget(user: users.elementAt(index));
        },
        itemCount: userSize
    );
  }

  Widget buildArticleListView(){
    return buildListView(
        itemWidget: (index){
          return OscSearchArticleWidget(article: articles.elementAt(index));
        },
        itemCount: articleSize
    );
  }

  search(String text){
    isHistoryPage = false;
    keyword = text;
    editingController.text = text;
    _addKeyword(keyword);
    clearList();
    refreshController.requestRefresh();
  }

  refresh() async{
    clearList();
    await loadData();
  }

  clearList(){
    pageToken = null;
    articleSize = 0;
    articleTotalCount = 0;
    userSize = 0;
    userTotalCount = 0;
    softSize = 0;
    softwareTotalCount = 0;
    articles?.clear();
    users?.clear();
    softWares?.clear();
  }

  loadData() async{
    await httpRepository.searchArticle(keyword: keyword, pageToken: pageToken, order: order).then((resp){
      if(resp != null){
        if(resp.success && resp.result != null){
          OscSearchResultEntity entity = resp.result;
          if(pageToken == null){
            userTotalCount = entity.userCount;
            users = entity.users;
            userSize = users?.length??0;
            articleTotalCount = entity.articleCount;
            articles = entity.articles;
            articleSize = articles?.length??0;
            softwareTotalCount = entity.softwareCount;
            softWares = entity.softWares;
            softSize = softWares?.length??0;
          } else {
            articles.addAll(entity.articles);
          }
          pageToken = entity.nextPageToken;
          articleSize = articles?.length??0;
          if(articleSize == articleTotalCount){
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
          refreshController.refreshCompleted();
          if (mounted) {
            setState(() {

            });
          }
        }
      }
    });
  }

  _addKeyword(String keyword){
    if(keywordList.contains(keyword)){
      keywordList.remove(keyword);
    }
    keywordList.insert(0, keyword);
    keywordSize = keywordList.length;
    SearchKeywordData().add(keyword: keyword);
    if(mounted){
      setState(() {

      });
    }
  }

  _clearKeyword(){
    keywordList.clear();
    keywordSize = 0;
    SearchKeywordData().clear();
    if(mounted){
      setState(() {

      });
    }
  }

  jump2Page(Widget page){
    NavigatorUtil.pushPage(context, page);
  }

  showToast(String msg){
    PdUtil.showToast(msg: msg);
  }

}